package com.aat.dxfy.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class JDBC {

	private static JDBC jdbc = null;
	private static List<Connection> cons = new CopyOnWriteArrayList<Connection>();
	private static int poolSize = 1;

	// 双重检查
	public static synchronized JDBC newInstance() {
		if (null == jdbc) {
			synchronized (JDBC.class) {
				if (null == jdbc)
					jdbc = new JDBC();
			}
		}
		return jdbc;
	}

	private JDBC() {
		for (int i = 0; i < poolSize; i++) {
			cons.add(getConnection());
		}
		System.out.println("cons=" + cons.size());
	}

	public static Connection getCon() {
		Connection con = null;
		if (cons.size() > 0) {
			con = cons.get(0);
			cons.remove(0);
		}
		System.out.println("连接池：" + cons.size());
		return con;
	}

	public static synchronized void release(Connection con) {
		cons.add(con);
	}

	public static void closeAll() {
		for (int i = 0; i < cons.size(); i++) {
			try {
				cons.get(i).close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		cons.clear();
	}

	private static Connection getConnection() {
		Config c = new Config(JDBC.class.getResourceAsStream("config.properties"));
		String driver = c.getString("driver");
		String url = c.getString("url");
		String user = c.getString("user");
		String passwd = c.getString("passwd");
		poolSize = c.getInt("poolSize");
		try {
			Class.forName(driver);
			return DriverManager.getConnection(url, user, passwd);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("驱动加载错误或者没有找到驱动包!");
			return null;
		}
	}

}
